package com.cx.zhshopping.http;


import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;

import io.reactivex.observers.DisposableObserver;


/**
 * Created by goldze on 2017/5/10.
 * 统一的Code封装处理。该类仅供参考，实际业务逻辑, 根据需求来定义，
 */

public abstract class ApiDisposableObserver<T> extends DisposableObserver<T> {
    public abstract void onResult(T t);

    @Override
    public void onComplete() {

    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
//        if (e instanceof ResponseThrowable) {
//            ResponseThrowable rError = (ResponseThrowable) e;
//            ToastUtils.showShort(rError.toString());
//            return;
//        }
        //其他全部甩锅网络异常
//        ToastUtils.showShort("网络异常");

        ToastUtils.showShort(e.getMessage());
    }

    @Override
    public void onStart() {
        super.onStart();
//        ToastUtils.showShort("http is start");
        // if  NetworkAvailable no !   must to call onCompleted
        if (!NetworkUtil.isNetworkAvailable(Utils.getApp())) {
//            KLog.d("无网络，读取缓存数据");
            onComplete();
        }
    }

    @Override
    public void onNext(Object o) {
        BaseResponse baseResponse = (BaseResponse) o;
        switch (baseResponse.getStatus()) {
            case CodeRule.CODE_0:
                //请求成功, 正确的操作方式
                onResult((T) baseResponse);
                break;
            case CodeRule.CODE_1:
                // 请求成功, 正确的操作方式, 并消息提示
                onResult((T) baseResponse);
                break;
            case CodeRule.CODE_2:
                onResult((T)baseResponse);
                break;
            case CodeRule.CODE_3:
//                App.getInstance().sendLoginOut();
                break;
            default:
                ToastUtils.showShort("请求错误:",baseResponse.getStatus()+ baseResponse.getMessage());
//                onResult((T) baseResponse);
                break;
        }
    }

    public static final class CodeRule {
        //请求成功, 正确的操作方式
        static final int CODE_0 = 0;
        //请求成功, 消息提示
        static final int CODE_1 = 1;
        static final int CODE_2 = 2;
        static final int CODE_3 = 3;
    }
}